﻿using SimpleBoard.Backend.Client.Models;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

namespace SimpleBoard.Backend.Client.Services
{
    public interface IDeviceService
    {
        Task<ApiResult<Device[]>> GetDeviceAsync();
        Task<ApiResult<DeviceType[]>> GetDeviceTypeAsync();
        Task<ApiResult<object>> AddDeviceTypeAsync(Backend.Pages.DeviceTypeAddPage.DeviceTypeModel model);
        Task<ApiResult<object>> AddDeviceAsync(Backend.Pages.DeviceAddPage.DeviceModel model);
    }

    public class DeviceService : IDeviceService
    {
        private readonly HttpClient _httpClient;

        public DeviceService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<ApiResult<DeviceType[]>> GetDeviceTypeAsync()
        {
            return await _httpClient.GetFromJsonAsync<ApiResult<DeviceType[]>>("/api/Device/GetDeviceTypes");
        }

        public async Task<ApiResult<Device[]>> GetDeviceAsync()
        {
            return await _httpClient.GetFromJsonAsync<ApiResult<Device[]>>("/api/Device/GetDevices");
        }

        public async Task<ApiResult<object>> AddDeviceTypeAsync(Backend.Pages.DeviceTypeAddPage.DeviceTypeModel model)
        {
            // ResisterDevice
            var resp = await _httpClient.PostAsync("/api/Device/ResisterDevice", new FormUrlEncodedContent(new Dictionary<string, string>()
            {
                {"name", model.Name},
                {"descriptionJson", model.ProtocolJson},
            }));

            var content = await resp.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResult<object>>(content, new JsonSerializerOptions
            {
                 PropertyNameCaseInsensitive = true,
            }); 

            return result;
        }

        public async Task<ApiResult<object>> AddDeviceAsync(Backend.Pages.DeviceAddPage.DeviceModel model)
        {
            // ResisterDevice
            var resp = await _httpClient.PostAsync("/api/Device/AddDevice", new FormUrlEncodedContent(new Dictionary<string, string>()
            {
                {"name", model.Name},
                {"resistryId", model.Type.ToString()},
            }));

            var content = await resp.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResult<object>>(content, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            });

            return result;
        }
    }
}
